package it.lorenz.server.fk.business.mail;

import it.lorenz.server.fk.business.AbstractBusinessService;
import it.lorenz.server.fk.business.AbstractDTO;
import it.lorenz.server.fk.business.ex.AbstractBusinessException;
import it.lorenz.server.fk.business.ex.ValidationException;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;

public class MailBusinessService extends AbstractBusinessService {

    @Autowired
    private IMailManager mailManager;
    @Autowired
    private IMailValidator mailValidator;

    @Override
    public void doFormalValidation(AbstractDTO dto) throws ValidationException {
        if (mailValidator != null) {
            mailValidator.doFormalValidation((MailDTO) dto);
        }
    }

    @Override
    public void doFunctionalValidation(AbstractDTO dto)
       throws ValidationException {
        if (mailValidator != null) {
            mailValidator.doFunctionalValidation((MailDTO) dto);
        }
    }

    @Override
    public AbstractDTO callBusinessService(AbstractDTO dto)
       throws AbstractBusinessException {
        MailDTO mailDTO = (MailDTO) dto;

        try {
            mailManager.send(mailDTO.getFrom(), mailDTO.getBounceEmail(),
               mailDTO.getTos(), mailDTO.getCcs(), mailDTO.getBccs(),
               mailDTO.getSubject(), mailDTO.getMessage(), mailDTO
               .isHtmlFormatted(), mailDTO.getAttachments());
        } catch (EmailException e) {
            throw new MailException(e.getMessage(), e);
        }

        return mailDTO;
    }

    public void setMailManager(IMailManager mailManager) {
        this.mailManager = mailManager;
    }

    public void setMailValidator(IMailValidator mailValidator) {
        this.mailValidator = mailValidator;
    }
}
